<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.refundAddrId ? $t('shop.newShipAdd') : $t('shop.modifyShipAdd')"
    :close-on-click-modal="false"
    :append-to-body="true"
    class="dialog-add-or-update"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="80px"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('publics.addressee')"
        prop="receiverName"
      >
        <el-input
          v-model="dataForm.receiverName"
          maxlength="36"
          show-word-limit
          :placeholder="$t('shop.consigneeName')"
          class="el-form-item"
        />
      </el-form-item>

      <el-form-item
        :label="$t('publics.mobilePhone')"
        prop="receiverMobile"
      >
        <el-input
          v-model="dataForm.receiverMobile"
          maxlength="11"
          show-word-limit
          :placeholder="$t('publics.mobilePhone')"
        />
      </el-form-item>
      <el-form-item
        :label="$t('shop.companyLandline')"
        prop="receiverTelephone"
      >
        <el-input
          v-model="dataForm.receiverTelephone"
          maxlength="30"
          show-word-limit
          :placeholder="$t('shop.companyLandline')"
        />
      </el-form-item>
      <el-form-item
        :label="$t('address.province')"
        required
      >
        <el-col :span="8">
          <el-form-item prop="provinceId">
            <el-select
              v-model="dataForm.provinceId"
              :placeholder="$t('tip.select')"
              :disabled="pickerDisabled"
              @change="onSelectProvince"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="cityId">
            <el-select
              v-model="dataForm.cityId"
              :placeholder="$t('tip.select')"
              :disabled="pickerDisabled"
              @change="onSelectCity"
            >
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="areaId">
            <el-select
              v-model="dataForm.areaId"
              :placeholder="$t('tip.select')"
              :disabled="pickerDisabled"
            >
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item
        :label="$t('address.detailed')"
        prop="addr"
      >
        <el-input
          v-model="dataForm.addr"
          :placeholder="$t('address.detailed')"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item
        :label="$t('address.postalCode')"
        prop="postCode"
      >
        <el-input
          v-model="dataForm.postCode"
          :placeholder="$t('address.postalCode')"
          maxlength="6"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('crud.filter.cancelBtn') }}
        </div>
        <div
          class="primary-btn default-btn"
          @click="onSubmit()"
        >
          {{ $t('crud.filter.submitBtn') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { isMobile, isStarMobile, isPhone, isPhoneStar } from '@/utils/validate'
// eslint-disable-next-line no-unused-vars
const validatePostCode = (rule, value, callback) => {
  if (/^\s+$/g.test(value)) {
    callback(new Error('不能全为空格'))
    return
  }
  if (!/^[0-9]{6}$/.test(value) && value !== '') {
    callback(new Error('请输入正确的邮政编码'))
    return
  }
  callback()
}
// eslint-disable-next-line no-unused-vars
const validateNotEmpty = (rule, value, callback) => {
  if (value.trim() === '') {
    callback(new Error($t('order.cannotEmpty')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateReceiverName = (rule, value, callback) => {
  if (value.trim() === '') {
    callback(new Error($t('shop.coneeNameCanEmpty')))
  } else {
    callback()
  }
}

// eslint-disable-next-line no-unused-vars
const validateReceiverMobile = (rule, value, callback) => {
  if (dataForm.refundAddrId ? !isStarMobile(value) : !isMobile(value)) {
    callback(new Error($t('shop.pleeNormaeNumF')))
  } else {
    callback()
  }
}

// eslint-disable-next-line no-unused-vars
const validateReceiverTelephone = (rule, value, callback) => {
  if (value && (dataForm.refundAddrId ? !isPhoneStar(value) : !isPhone(value))) {
    callback(new Error($t('shop.phoneErrorTips')))
  } else {
    callback()
  }
}

const dataRule = {
  postCode: [
    {
      validator: validatePostCode,
      trigger: 'blur'
    }
  ],
  receiverName: [
    { required: true, message: $t('shop.coneeNameCanEmpty'), trigger: 'blur' },
    { validator: validateReceiverName, trigger: 'blur' }
  ],
  addr: [
    { required: true, message: $t('shop.addressCannotBeEmpty'), trigger: 'blur' },
    { validator: validateNotEmpty, trigger: 'blur' }
  ],
  cityId: [{ required: true, message: $t('shop.cityCannotBeEmpty'), trigger: 'change' }],
  provinceId: [{ required: true, message: $t('shop.provinceCannotBeEmpty'), trigger: 'change' }],
  areaId: [{ required: true, message: $t('shop.districtCounEmpty'), trigger: 'change' }],
  receiverMobile: [
    { required: true, message: $t('sys.mobilePhoneNoNull'), trigger: 'blur' },
    { validator: validateReceiverMobile, trigger: 'blur' }
  ],
  receiverTelephone: [
    { validator: validateReceiverTelephone, trigger: 'blur' }
  ]
}

const provinceList = ref([]) // 省列表
const cityList = ref([]) // 市列表
const areaList = ref([]) // 区列表
const dataForm = reactive({
  refundAddrId: null,
  addrId: 0,
  addr: '',
  receiverName: '',
  receiverMobile: '',
  receiverTelephone: '',
  postCode: '',
  area: '',
  city: '',
  province: '',
  areaId: null,
  cityId: null,
  provinceId: null,
  defaultAddr: 1
})
const isSubmit = ref(false)
const dataFormRef = ref(null)
const visible = ref(false)
const pickerDisabled = ref(false)
const init = async id => {
  dataForm.refundAddrId = id || 0
  visible.value = true
  pickerDisabled.value = false
  isSubmit.value = false
  nextTick(() => {
    dataFormRef.value?.resetFields()
    cityList.value = []
    areaList.value = []
    dataForm.provinceId = null
    dataForm.cityId = null
    dataForm.areaId = null
  })
  onListAreaByParentId().then(({ data }) => {
    provinceList.value = data
  })
  // 等待地址信息返回
  provinceList.value = await onGetAreaListInfo()
  if (dataForm.refundAddrId) {
    http({
      url: http.adornUrl(`/shop/refundAddr/info/${dataForm.refundAddrId}`),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.addr = data.addr
      dataForm.receiverMobile = data.receiverMobile
      dataForm.receiverTelephone = data.receiverTelephone
      dataForm.areaId = data.areaId
      dataForm.cityId = data.cityId
      dataForm.provinceId = data.provinceId
      dataForm.receiverName = data.receiverName
      dataForm.postCode = data.postCode
      dataForm.defaultAddr = data.defaultAddr
      onGetProvCityArea()
      onListAreaByParentId(data.provinceId).then(({ data }) => {
        cityList.value = data
      })
      onListAreaByParentId(data.cityId).then(({ data }) => {
        areaList.value = data
      })
    })
  }
}
const onListAreaByParentId = pid => {
  const paramData = {}
  if (!pid) {
    paramData.level = 1
  } else {
    paramData.pid = pid
  }
  return http({
    url: http.adornUrl('/admin/area/listByPid'),
    method: 'get',
    params: http.adornParams(paramData)
  })
}
// 获取省市区列表
const onGetProvCityArea = () => {
  for (const proItem of provinceList.value) {
    if (proItem.areaId === dataForm.provinceId) {
      cityList.value = proItem.areas
      for (const cityItem of cityList.value) {
        if (cityItem.areaId === dataForm.cityId) {
          areaList.value = cityItem.areas
          break
        }
      }
      break
    }
  }
}
// 获取地址列表
const onGetAreaListInfo = () => {
  return new Promise(resolve => {
    http({
      url: http.adornUrl('/admin/area/areaListInfo'),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      resolve(data)
    })
  })
}
const onGetCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}
// 选择省
const onSelectProvince = val => {
  dataForm.cityId = null
  dataForm.city = ''
  // 获取城市的select
  const { curNode, areas } = onGetCurrentChild(provinceList.value, val)
  if (areas) {
    cityList.value = areas
  } else {
    onListAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      cityList.value = data
    })
  }
  // 清除区级信息
  dataForm.areaId = null
  dataForm.area = ''
  areaList.value = []
}
// 选择市
const onSelectCity = val => {
  dataForm.areaId = null
  dataForm.area = ''
  // 获取区的select
  const { curNode, areas } = onGetCurrentChild(cityList.value, val)
  if (areas) {
    areaList.value = areas
  } else {
    onListAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      areaList.value = data
    })
  }
}
const emit = defineEmits(['refreshDataList'])
// 表单提交
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const onSubmit = () => {
  for (let i = 0; i < provinceList.value.length; i++) {
    if (provinceList.value[i].areaId === dataForm.provinceId) {
      // 将省名字保存起来
      dataForm.province = provinceList.value[i].areaName
      break
    }
  }
  for (let i = 0; i < cityList.value.length; i++) {
    if (cityList.value[i].areaId === dataForm.cityId) {
      // 将市名字保存起来
      dataForm.city = cityList.value[i].areaName
      break
    }
  }
  for (let i = 0; i < areaList.value.length; i++) {
    if (areaList.value[i].areaId === dataForm.areaId) {
      // 将市名字保存起来
      dataForm.area = areaList.value[i].areaName
      break
    }
  }
  dataFormRef.value.validate(valid => {
    if (valid) {
      if (isSubmit.value) {
        return false
      }
      isSubmit.value = true
      pickerDisabled.value = true
      http({
        url: http.adornUrl('/shop/refundAddr'),
        method: dataForm.refundAddrId ? 'put' : 'post',
        data: http.adornData({
          refundAddrId: dataForm.refundAddrId || undefined,
          addr: dataForm.addr,
          receiverName: dataForm.receiverName,
          receiverMobile: dataForm.receiverMobile,
          receiverTelephone: dataForm.receiverTelephone,
          area: dataForm.area,
          city: dataForm.city,
          province: dataForm.province,
          areaId: dataForm.areaId,
          cityId: dataForm.cityId,
          provinceId: dataForm.provinceId,
          postCode: dataForm.postCode,
          defaultAddr: dataForm.defaultAddr
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList', page.value)
          }
        })
      }).catch(() => {
        isSubmit.value = false
        pickerDisabled.value = false
      })
    }
  })
}
defineExpose({ init })
</script>
<style lang="scss" scoped>
.dialog-add-or-update{
  .el-form-item {
  padding-bottom: 7px;
}
}
</style>
